package io.github.mymonstercat.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class HwNLPUtils {

    // 从配置文件中加载URL
    @Value("${hwnlp.api-url}")
    private String apiUrl;

    public String requestPYNLPApi(String str1, String str2) throws IOException {
        // 创建请求数据
        Map<String, String> requestData = new HashMap<>();
        requestData.put("str1", str1);
        requestData.put("str2", str2);

        // 将请求数据转换为 JSON 字符串
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String json = objectMapper.writeValueAsString(requestData);
            System.out.println(json);
            // 创建 HTTP 客户端
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(apiUrl);
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setEntity(new StringEntity(json, "UTF-8"));

            // 发送请求并获取响应
            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity resEntity = response.getEntity();
            String responseString = EntityUtils.toString(resEntity, "UTF-8");
            System.out.println(responseString);
            response.close();
            return responseString;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public String requestPYNLPListApi(String[] hwOCRTexts, String[] configTexts) throws IOException {

        // 创建请求数据
        Map<String, String[]> requestData = new HashMap<>();
        requestData.put("hwOCRTexts", hwOCRTexts);
        requestData.put("configTexts", configTexts);

        // 将请求数据转换为 JSON 字符串
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String json = objectMapper.writeValueAsString(requestData);
            System.out.println("Request JSON: " + json);

            // 创建 HTTP 客户端
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(apiUrl);
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setEntity(new StringEntity(json, "UTF-8"));

            // 发送请求并获取响应
            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity resEntity = response.getEntity();
            String responseString = EntityUtils.toString(resEntity, "UTF-8");
            System.out.println("Response: " + responseString);
            response.close();
            return responseString;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String requestNLPText(String promptWord) throws IOException {
        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(30, TimeUnit.SECONDS) // 设置读取超时时间为30秒
                .build();

        // 请求的 URL
        String url = "http://10.40.37.223:8092/v1/chat/completions";

        // 构建 JSON 对象
        JSONObject messageObject = new JSONObject();
        messageObject.put("content", promptWord);

        JSONArray messagesArray = new JSONArray();
        messagesArray.add(messageObject);

        JSONObject requestObject = new JSONObject();
        requestObject.put("max_tokens", 600);
        requestObject.put("temperature", 0.1);
        requestObject.put("messages", messagesArray);

        // 输出生成的 JSON 字符串
        System.out.println(requestObject.toString());

        // 创建请求体
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), requestObject.toString());

        // 构建请求
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("Content-Type", "application/json")
                .build();

        // 最大重试次数
        final int MAX_RETRIES = 3;
        int attempt = 0;
        Response response = null;
        String responseBodyStr = null;
        while (attempt < MAX_RETRIES) {
            try {
                // 执行请求
                response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    // 在关闭响应之前，先获取响应体内容
                    responseBodyStr = Objects.requireNonNull(response.body()).string();
                    return responseBodyStr;  // 返回响应体内容
                } else {
                    log.info("Request failed with status code: " + response.code());
                }
            } catch (IOException e) {
                log.info("IOException occurred while making the request. Attempt " + (attempt + 1));
            } finally {
                if (response != null) {
                    response.close();  // 确保关闭响应体
                }
            }

            // 增加重试计数
            attempt++;
            // 如果尝试次数已达到最大值
            if (attempt >= MAX_RETRIES) {
                throw new IOException("Failed to get response from Huawei NLP after " + MAX_RETRIES + " attempts.");
            }
        }

        System.err.println("请求NLP接口失败，已重试" + MAX_RETRIES + "次");
        return null; // 返回失败的状态
    }


    // 将字符串转换为Unicode转义形式的方法
    public static String toUnicodeEscaped(String input) {
        StringBuilder unicodeStr = new StringBuilder(input.length() * 6);
        for (char c : input.toCharArray()) {
            if (c < 128) {
                // ASCII字符无需转换
                unicodeStr.append(c);
            } else {
                unicodeStr.append(String.format("\\u%04x", (int) c));
            }
        }
        return unicodeStr.toString().replace("\\\\u", "\\u");
    }

//    public static void main(String[] args) throws IOException {
//        String ss = requestNLPText("附服务合同类进度结算确认单经办人段志娥2024年8月6日单位元合同相对人蒙自红惠汽车服务有限公司合同名hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh");
//        System.out.println(ss);
//    }
}
